import config from '@/config';
import { ADMIN } from '@/config/default';
import { formatFullPath } from '@/utils/i18n';
import { filterMenu } from '@/utils/authority-utils';
import { getLocalSetting } from '@/utils/themeUtil';
import deepClone from 'lodash.clonedeep';
import { pres } from '@/utils/pres';
import { getRingstoneApi } from '@/services/user.js'
const localSetting = getLocalSetting(true);
const customTitlesStr = sessionStorage.getItem(process.env.VUE_APP_TBAS_TITLES_KEY);
const customTitles = (customTitlesStr && JSON.parse(customTitlesStr)) || [];
import moment from 'moment';
export default {
  namespaced: true,
  state: {
    ringstoneList: [],
    isMobile: false,
    animates: ADMIN.animates,
    palettes: ADMIN.palettes,
    pageMinHeight: 0,
    menuData: [],
    collapsed: true,
    activatedFirst: undefined,
    customTitles,
    ...config,
    ...localSetting,
    acarsTime: '',
    fraAcarsTime: '',
    helpFlag: false,
    versionFlag: false,
    videoFlag: false,
    versionReadFlag: localStorage.getItem('versionReadFlag') ? localStorage.getItem('versionReadFlag') : false,
    pt: 16,
    baseAppNameShow: process.env.VUE_APP_CURENV === 'development' || process.env.VUE_APP_CURENV === 'production',
    keepAlivePage: ['FraMonitoring'],
    historicalSegmentPointReversed: localStorage.getItem('hspr') ? localStorage.getItem('hspr') !== 'false' : true,
    openType: localStorage.getItem('openType') ? localStorage.getItem('openType') : '_self',
    fleetStatusClickEvent: localStorage.getItem('fleetStatusClickEvent') ? localStorage.getItem('fleetStatusClickEvent') : true
  },
  getters: {
    sideMenuWidth(state) {
      return state.collapsed ? '56px' : '160px';
    },
    appBaseName(state) {
      return state.baseAppNameShow ? process.env.VUE_APP_BASE_NAME : '';
    },
    menuData(state, getters, rootState) {
      if (state.filterMenu) {
        const menuList = state.menuData;

        const mr = pres(menuList);
        const { permissions, roles } = rootState.account;
        return filterMenu(deepClone(mr), permissions, roles);
      }
      return state.menuData;
    },
    firstMenu(state, getters) {
      const { menuData } = getters;
      if (menuData.length > 0 && !menuData[0].fullPath) {
        formatFullPath(menuData);
      }
      return menuData.map(item => {
        const menuItem = { ...item };
        delete menuItem.children;
        return menuItem;
      });
    },
    subMenu(state) {
      const { menuData, activatedFirst } = state;
      if (menuData.length > 0 && !menuData[0].fullPath) {
        formatFullPath(menuData);
      }
      const current = menuData.find(menu => menu.fullPath === activatedFirst);
      return current && current.children || [];
    }
  },
  mutations: {
    setRingstone(state, p) {
      state.ringstoneList = p
    },
    setCollapsed(state, collapsed) {
      state.collapsed = collapsed;
    },
    setAcarsTime(state, acarsTime) {
      state.acarsTime = moment.utc(new Date()).format('YYYY-MM-DD HH:mm:ss');
    },
    setFraAcarsTime(state, acarsTime) {
      state.fraAcarsTime = moment.utc(new Date()).format('YYYY-MM-DD HH:mm:ss');
    },
    setState(state, { key, payload }) {
      state[key] = payload;
    },
    setDevice(state, isMobile) {
      state.isMobile = isMobile;
    },
    setTheme(state, theme) {
      state.theme = theme;
    },
    setLayout(state, layout) {
      state.layout = layout;
    },
    setMultiPage(state, multiPage) {
      state.multiPage = multiPage;
    },
    setAnimate(state, animate) {
      state.animate = animate;
    },
    setWeekMode(state, weekMode) {
      state.weekMode = weekMode;
    },
    setFixedHeader(state, fixedHeader) {
      state.fixedHeader = fixedHeader;
    },
    setFixedSideBar(state, fixedSideBar) {
      state.fixedSideBar = fixedSideBar;
    },
    setLang(state, lang) {
      state.lang = lang;
    },
    setHideSetting(state, hideSetting) {
      state.hideSetting = hideSetting;
    },
    correctPageMinHeight(state, minHeight) {
      state.pageMinHeight += minHeight;
    },
    setMenuData(state, menuData) {
      state.menuData = menuData;
    },
    setAsyncRoutes(state, asyncRoutes) {
      state.asyncRoutes = asyncRoutes;
    },
    setPageWidth(state, pageWidth) {
      state.pageWidth = pageWidth;
    },
    setActivatedFirst(state, activatedFirst) {
      state.activatedFirst = activatedFirst;
    },
    setFixedTabs(state, fixedTabs) {
      state.fixedTabs = fixedTabs;
    },
    setCustomTitle(state, { path, title }) {
      if (title) {
        const obj = state.customTitles.find(item => item.path === path);
        if (obj) {
          obj.title = title;
        } else {
          state.customTitles.push({ path, title });
        }
        sessionStorage.setItem(process.env.VUE_APP_TBAS_TITLES_KEY, JSON.stringify(state.customTitles));
      }
    }
  },
  actions: {
    setAcarsTime({ commit, dispatch }) {
      commit('setAcarsTime');
    },
    showVersion({ state, commit, dispatch }, payload = {}) {
      if (payload.checkRead) {
        if (!state.versionReadFlag) {
          commit('setState', { key: 'versionFlag', payload: !state.baseAppNameShow });
        }
      } else {
        commit('setState', { key: 'versionFlag', payload: !state.baseAppNameShow });
      }
    },
    async messageAudioHandler({ commit }, payload) {
      // var MessageAudio = document.getElementById('MessageAudio');
      // MessageAudio.play();
      const res = await getRingstoneApi(payload)
      commit('setRingstone', res.data)
    },
    setPageHeight({ commit }) {
      setTimeout(() => {
        const ch = (document.querySelector('.comm-search') || document.querySelector('.comm-search-f'))?.clientHeight ?? 0;
        const pt = ch ? ch - -32 : 16;
        commit('setState', { key: 'pt', payload: pt });
      }, 0);
    },
    setFraAcarsTime({ commit, dispatch }) {
      commit('setFraAcarsTime');
    }
  }
};
